import { api } from '../../utils/api';

Page({
  data: {
    user: null as any,
  },

  onLoad() {
    this.checkLogin();
    this.loadUserInfo();
  },

  onShow() {
    this.loadUserInfo();
  },

  async checkLogin() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login',
      });
      return;
    }
    api.setToken(token);
  },

  async loadUserInfo() {
    try {
      // 优先从缓存读取用户信息
      const cachedUser = wx.getStorageSync('currentUser');
      if (cachedUser) {
        this.setData({
          user: cachedUser,
        });
      }
      
      // 同时从后端获取最新用户信息并更新缓存
      const res: any = await api.getCurrentUser();
      if (res.success && res.user) {
        // 更新缓存
        wx.setStorageSync('currentUser', res.user);
        // 更新页面数据
        this.setData({
          user: res.user,
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      // 如果接口失败，至少使用缓存的数据
      const cachedUser = wx.getStorageSync('currentUser');
      if (cachedUser) {
        this.setData({
          user: cachedUser,
        });
      }
    }
  },

  onEditProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit-profile',
    });
  },

  onMyQRCode() {
    wx.navigateTo({
      url: '/pages/qrcode/qrcode',
    });
  },

  onLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          api.clearToken();
          // 清除用户信息缓存
          wx.removeStorageSync('currentUser');
          wx.redirectTo({
            url: '/pages/login/login',
          });
        }
      },
    });
  },
});

